package com.stcc.dataConfig.impl.ecommerce;

import com.alibaba.fastjson.JSONObject;
import com.stcc.base.bo.ResponseBase;
import com.stcc.base.util.HttpUrlConnectionUtil;
import com.stcc.dataConfig.service.ecommerce.JingDongQgService;
import com.stcc.dataConfig.utils.RushToPurchase;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.webkit.network.CookieManager;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.CookieHandler;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述:
 * 项目名:stcc_gl-parent
 * 包名:com.stcc.dataConfig.impl.ecommerce
 * 作者:stcc
 * 创建时间:2021/4/29 15:56
 * 版本:1.0
 */
@Component
@DubboService
public class JingDongQgServiceImpl implements JingDongQgService {
    final static String headerAgent = "User-Agent";
    final static String headerAgentArg = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36";
    final static String Referer = "Referer";
    final static String RefererArg = "https://passport.jd.com/new/login.aspx";
    static Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>(16);
    public static CookieManager manager = new CookieManager();
    public static String ticket = "";
    //eid
    public static String eid = "W2HEXZSRULGOBXAMFF6J44UTIGCP5QGKRQO5M7KZHYUAU7RT2JBTXRG2ZNRUWHKYX2PHNKRJI2KOM7BZIZ2V3F3C64";
    //fp
    public static String fp = "4ce08fcab2f99f47724c9c7cdf771d9f";
    @Value("${pid}")
    private String pid;
    @Override
    public ResponseBase jingDongQg() {
        CookieHandler.setDefault(manager);

        JSONObject headers = new JSONObject();
        headers.put(headerAgent, headerAgentArg);
        headers.put(Referer, RefererArg);

        Long now = System.currentTimeMillis();
        URI url = null;
        try {
            url = new URI("https://qr.m.jd.com/show?appid=133&size=147&t=" + now);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        Map<String, List<String>> stringListMap = new HashMap<String, List<String>>();
        stringListMap = manager.get(url, requestHeaders);
        List cookieList = stringListMap.get("Cookie");
        String cookies = cookieList.get(0).toString();
        String token = cookies.split("wlfstk_smdl=")[1];
        headers.put("Cookie", cookies);
        //判断是否扫二维码
        while (true) {
            String checkUrl = "https://qr.m.jd.com/check?appid=133&callback=jQuery" + (int) ((Math.random() * (9999999 - 1000000 + 1)) + 1000000) + "&token=" + token + "&_=" + System.currentTimeMillis();
            String qrCode = HttpUrlConnectionUtil.get(headers, checkUrl);
            if (qrCode.indexOf("二维码未扫描") != -1) {
                System.out.println("二维码未扫描，请扫描二维码登录");
            } else if (qrCode.indexOf("请手机客户端确认登录") != -1) {
                System.out.println("请手机客户端确认登录");
            } else {
                ticket = qrCode.split("\"ticket\" : \"")[1].split("\"\n" +
                        "}\\)")[0];
                System.out.println("已完成二维码扫描登录");
                close();
                break;
            }
            try {
                Thread.sleep(3000);
                //验证，获取cookie
                String qrCodeTicketValidation = HttpUrlConnectionUtil.get(headers, "https://passport.jd.com/uc/qrCodeTicketValidation?t=" + ticket);
                stringListMap = manager.get(url, requestHeaders);
                cookieList = stringListMap.get("Cookie");
                cookies = cookieList.get(0).toString();
                headers.put("Cookie", cookies);

                //判断是否开始抢购
                    judgePruchase(headers);
                //开始抢购
                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 1000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
                for (int i = 0; i < 5; i++) {
                    threadPoolExecutor.execute(new RushToPurchase());
                }
                new RushToPurchase().run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static void close() {
//        通过窗口标题获取窗口句柄
        WinDef.HWND hWnd;
        final User32 user32 = User32.INSTANCE;
        user32.EnumWindows((hWnd1, arg1) -> {
            char[] windowText = new char[512];
            user32.GetWindowText(hWnd1, windowText, 512);
            String wText = Native.toString(windowText);
            // get rid of this if block if you want all windows regardless of whether
            // or not they have text
            if (wText.isEmpty()) {
                return true;
            }
            if (wText.contains("照片")) {
                hWnd1 = User32.INSTANCE.FindWindow(null, wText);
                WinDef.LRESULT lresult = User32.INSTANCE.SendMessage(hWnd1, 0X10, null, null);
            }
            return true;
        }, null);
    }
    public void judgePruchase(JSONObject headers)  {
        //获取开始时间
        JSONObject shopDetail = JSONObject.parseObject(HttpUrlConnectionUtil.get(headers, "https://item-soa.jd.com/getWareBusiness?skuId=" + pid));
        if (shopDetail.get("yuyueInfo") != null) {
            String buyDate = JSONObject.parseObject(shopDetail.get("yuyueInfo").toString()).get("buyTime").toString();
            String startDate = buyDate.split("-202")[0] + ":00";
            Long startTime = null;
            try {
                startTime = HttpUrlConnectionUtil.dateToTime(startDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //开始抢购
            while (true) {
                //获取京东时间
                JSONObject jdTime = JSONObject.parseObject(HttpUrlConnectionUtil.get(headers, "https://a.jd.com//ajax/queryServerData.html"));
                Long serverTime = Long.valueOf(jdTime.get("serverTime").toString());
                if (startTime >= serverTime) {
                    System.out.println("正在等待抢购时间");
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}
